package stud.mpgame.physics;

import java.util.ArrayList;

import com.sun.xml.internal.ws.wsdl.writer.document.soap12.Body;
import stud.mpgame.server.map.MapData;

/**
 * ...
 * @author pavel[f.pavel91@gmail.com]
 */
public class BroadPhase {

	private ArrayList< Circle > bodies; //circles
	
	public ArrayList< ArrayList< IBody > > cells;
	
	private static final int cellSize = 64;

    public BroadPhase(BroadPhase previous) {
        this.bodies = new ArrayList< Circle >();
        this.cells = previous.cells;
        this.width = previous.width;
        this.height = previous.height;
    }

	private int width;
	private int height;
	
	public BroadPhase(MapData gameMap) {
		this.bodies = new ArrayList<Circle>();
		this.cells = new ArrayList<ArrayList<IBody>>();
		
		this.width = gameMap.getWidth();
		this.height = gameMap.getHeight();
		for (int i = 0; i < height; ++i) {
			ArrayList<IBody> temp = new ArrayList<IBody>();
			for (int j = 0; j < width; ++j) {
				if (gameMap.getModel()[i * width + j] == 0) {
					temp.add(null);
				} else if (gameMap.getModel()[i * width + j] == 1) {
					temp.add(new AABB(cellSize * j, cellSize * (i + 1), cellSize * (j + 1), cellSize * i));
				} else if (gameMap.getModel()[i * width + j] == 2) {
					//temp.add(new Segment(/*cellSize * (i + 1), cellSize * j, new Vector2D(), new Vector2D()*/));
					temp.add(new AABB(cellSize * j, cellSize * (i + 1), cellSize * (j + 1), cellSize * i));
				}
			}
			cells.add(temp);
		}
		/*for (int i = 0; i < height; ++i) {
			String check = "";
			for (int j = 0; j < width; ++j) {
				if(cells.get(i).get(j) != null) {
                    System.out.println(cellSize * j + " " + cellSize * i + " " + cellSize * (j + 1) + " " +cellSize * (i + 1));
				}
				check += cells.get(i).get(j) == null ? " 0 " : " 1 ";
			}
            System.out.println(check);
		} */

	}

    public void update() {
        for(Circle body: bodies){
			int x = body.getCellX();
			int y = body.getCellY();
			for (int i = x - 1; i < x + 2; ++i)
				for (int j = y - 1; j < y + 2; ++j)
					if (i >= 0 && j >= 0 && j < height && i < width && cells.get(j).get(i) !=  null)
						cells.get(j).get(i).intersect(body);
		}
	}
	
	public void addCircle(Circle circle) {
		bodies.add(circle);
	}
	
	public void removeCircle(Circle circle) {
		bodies.remove(circle);
	}
	
}